home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / ruby / 1.8 / date.rb < prev    next >
Encoding:
Text File  |  2006-06-21  |  42.7 KB  |  1,329 lines

  1. #
  2. # date.rb - date and time library
  3. #
  4. # Author: Tadayoshi Funaba 1998-2006
  5. #
  6. # Documentation: William Webber <william@williamwebber.com>
  7. #
  8. #--
  9. # $Id: date.rb,v 2.15 2005-02-06 11:09:53+09 tadf Exp $
  10. #++
  11. #
  12. # == Overview
  13. #
  14. # This file provides two classes for working with
  15. # dates and times.
  16. #
  17. # The first class, Date, represents dates. 
  18. # It works with years, months, weeks, and days.
  19. # See the Date class documentation for more details.
  20. #
  21. # The second, DateTime, extends Date to include hours,
  22. # minutes, seconds, and fractions of a second.  It
  23. # provides basic support for time zones.  See the
  24. # DateTime class documentation for more details.
  25. #
  26. # === Ways of calculating the date.
  27. #
  28. # In common usage, the date is reckoned in years since or
  29. # before the Common Era (CE/BCE, also known as AD/BC), then
  30. # as a month and day-of-the-month within the current year.
  31. # This is known as the *Civil* *Date*, and abbreviated
  32. # as +civil+ in the Date class.
  33. #
  34. # Instead of year, month-of-the-year,  and day-of-the-month,
  35. # the date can also be reckoned in terms of year and
  36. # day-of-the-year.  This is known as the *Ordinal* *Date*,
  37. # and is abbreviated as +ordinal+ in the Date class.  (Note
  38. # that referring to this as the Julian date is incorrect.)
  39. #
  40. # The date can also be reckoned in terms of year, week-of-the-year,
  41. # and day-of-the-week.  This is known as the *Commercial*
  42. # *Date*, and is abbreviated as +commercial+ in the
  43. # Date class.  The commercial week runs Monday (day-of-the-week
  44. # 1) to Sunday (day-of-the-week 7), in contrast to the civil
  45. # week which runs Sunday (day-of-the-week 0) to Saturday
  46. # (day-of-the-week 6).  The first week of the commercial year
  47. # starts on the Monday on or before January 1, and the commercial
  48. # year itself starts on this Monday, not January 1.
  49. #
  50. # For scientific purposes, it is convenient to refer to a date
  51. # simply as a day count, counting from an arbitrary initial
  52. # day.  The date first chosen for this was January 1, 4713 BCE.
  53. # A count of days from this date is the *Julian* *Day* *Number*
  54. # or *Julian* *Date*, which is abbreviated as +jd+ in the
  55. # Date class.  This is in local time, and counts from midnight
  56. # on the initial day.  The stricter usage is in UTC, and counts
  57. # from midday on the initial day.  This is referred to in the
  58. # Date class as the *Astronomical* *Julian* *Day* *Number*, and
  59. # abbreviated as +ajd+.  In the Date class, the Astronomical
  60. # Julian Day Number includes fractional days.
  61. #
  62. # Another absolute day count is the *Modified* *Julian* *Day*
  63. # *Number*, which takes November 17, 1858 as its initial day.
  64. # This is abbreviated as +mjd+ in the Date class.  There
  65. # is also an *Astronomical* *Modified* *Julian* *Day* *Number*,
  66. # which is in UTC and includes fractional days.  This is
  67. # abbreviated as +amjd+ in the Date class.  Like the Modified
  68. # Julian Day Number (and unlike the Astronomical Julian
  69. # Day Number), it counts from midnight.
  70. #
  71. # Alternative calendars such as the Chinese Lunar Calendar,
  72. # the Islamic Calendar, or the French Revolutionary Calendar
  73. # are not supported by the Date class; nor are calendars that
  74. # are based on an Era different from the Common Era, such as
  75. # the Japanese Imperial Calendar or the Republic of China
  76. # Calendar.
  77. #
  78. # === Calendar Reform
  79. #
  80. # The standard civil year is 365 days long.  However, the
  81. # solar year is fractionally longer than this.  To account
  82. # for this, a *leap* *year* is occasionally inserted.  This
  83. # is a year with 366 days, the extra day falling on February 29. 
  84. # In the early days of the civil calendar, every fourth
  85. # year without exception was a leap year.  This way of
  86. # reckoning leap years is the *Julian* *Calendar*.
  87. #
  88. # However, the solar year is marginally shorter than 365 1/4
  89. # days, and so the *Julian* *Calendar* gradually ran slow
  90. # over the centuries.  To correct this, every 100th year
  91. # (but not every 400th year) was excluded as a leap year.
  92. # This way of reckoning leap years, which we use today, is
  93. # the *Gregorian* *Calendar*.
  94. #
  95. # The Gregorian Calendar was introduced at different times
  96. # in different regions.  The day on which it was introduced
  97. # for a particular region is the *Day* *of* *Calendar*
  98. # *Reform* for that region.  This is abbreviated as +sg+
  99. # (for Start of Gregorian calendar) in the Date class.
  100. #
  101. # Two such days are of particular
  102. # significance.  The first is October 15, 1582, which was
  103. # the Day of Calendar Reform for Italy and most Catholic
  104. # countries.  The second is September 14, 1752, which was
  105. # the Day of Calendar Reform for England and its colonies
  106. # (including what is now the United States).  These two
  107. # dates are available as the constants Date::ITALY and
  108. # Date::ENGLAND, respectively.  (By comparison, Germany and
  109. # Holland, less Catholic than Italy but less stubborn than
  110. # England, changed over in 1698; Sweden in 1753; Russia not
  111. # till 1918, after the Revolution; and Greece in 1923.  Many
  112. # Orthodox churches still use the Julian Calendar.  A complete
  113. # list of Days of Calendar Reform can be found at
  114. # http://www.polysyllabic.com/GregConv.html.)
  115. #
  116. # Switching from the Julian to the Gregorian calendar
  117. # involved skipping a number of days to make up for the
  118. # accumulated lag, and the later the switch was (or is)
  119. # done, the more days need to be skipped.  So in 1582 in Italy,
  120. # 4th October was followed by 15th October, skipping 10 days; in 1752
  121. # in England, 2nd September was followed by 14th September, skipping
  122. # 11 days; and if I decided to switch from Julian to Gregorian
  123. # Calendar this midnight, I would go from 27th July 2003 (Julian)
  124. # today to 10th August 2003 (Gregorian) tomorrow, skipping
  125. # 13 days.  The Date class is aware of this gap, and a supposed
  126. # date that would fall in the middle of it is regarded as invalid.
  127. #
  128. # The Day of Calendar Reform is relevant to all date representations
  129. # involving years.  It is not relevant to the Julian Day Numbers,
  130. # except for converting between them and year-based representations.
  131. #
  132. # In the Date and DateTime classes, the Day of Calendar Reform or
  133. # +sg+ can be specified a number of ways.  First, it can be as
  134. # the Julian Day Number of the Day of Calendar Reform.  Second,
  135. # it can be using the constants Date::ITALY or Date::ENGLAND; these
  136. # are in fact the Julian Day Numbers of the Day of Calendar Reform
  137. # of the respective regions.  Third, it can be as the constant
  138. # Date::JULIAN, which means to always use the Julian Calendar.
  139. # Finally, it can be as the constant Date::GREGORIAN, which means
  140. # to always use the Gregorian Calendar.
  141. #
  142. # Note: in the Julian Calendar, New Years Day was March 25.  The
  143. # Date class does not follow this convention.
  144. #
  145. # === Time Zones
  146. #
  147. # DateTime objects support a simple representation
  148. # of time zones.  Time zones are represented as an offset
  149. # from UTC, as a fraction of a day.  This offset is the
  150. # how much local time is later (or earlier) than UTC.
  151. # UTC offset 0 is centred on England (also known as GMT). 
  152. # As you travel east, the offset increases until you
  153. # reach the dateline in the middle of the Pacific Ocean;
  154. # as you travel west, the offset decreases.  This offset
  155. # is abbreviated as +of+ in the Date class.
  156. #
  157. # This simple representation of time zones does not take
  158. # into account the common practice of Daylight Savings
  159. # Time or Summer Time.
  160. #
  161. # Most DateTime methods return the date and the
  162. # time in local time.  The two exceptions are
  163. # #ajd() and #amjd(), which return the date and time
  164. # in UTC time, including fractional days.
  165. #
  166. # The Date class does not support time zone offsets, in that
  167. # there is no way to create a Date object with a time zone.
  168. # However, methods of the Date class when used by a
  169. # DateTime instance will use the time zone offset of this
  170. # instance.
  171. #
  172. # == Examples of use
  173. #
  174. # === Print out the date of every Sunday between two dates.
  175. #
  176. #     def print_sundays(d1, d2)
  177. #         d1 +=1 while (d1.wday != 0)
  178. #         d1.step(d2, 7) do |date|
  179. #             puts "#{Date::MONTHNAMES[date.mon]} #{date.day}"
  180. #         end
  181. #     end
  182. #
  183. #     print_sundays(Date::civil(2003, 4, 8), Date::civil(2003, 5, 23))
  184. #
  185. # === Calculate how many seconds to go till midnight on New Year's Day.
  186. #
  187. #     def secs_to_new_year(now = DateTime::now())
  188. #         new_year = DateTime.new(now.year + 1, 1, 1)
  189. #         dif = new_year - now
  190. #         hours, mins, secs, ignore_fractions = Date::day_fraction_to_time(dif)
  191. #         return hours * 60 * 60 + mins * 60 + secs
  192. #     end
  193. #
  194. #     puts secs_to_new_year()
  195.  
  196. require 'rational'
  197. require 'date/format'
  198.  
  199. # Class representing a date.
  200. #
  201. # See the documentation to the file date.rb for an overview.
  202. #
  203. # Internally, the date is represented as an Astronomical
  204. # Julian Day Number, +ajd+.  The Day of Calendar Reform, +sg+, is
  205. # also stored, for conversions to other date formats.  (There
  206. # is also an +of+ field for a time zone offset, but this
  207. # is only for the use of the DateTime subclass.)
  208. #
  209. # A new Date object is created using one of the object creation
  210. # class methods named after the corresponding date format, and the
  211. # arguments appropriate to that date format; for instance,
  212. # Date::civil() (aliased to Date::new()) with year, month,
  213. # and day-of-month, or Date::ordinal() with year and day-of-year.
  214. # All of these object creation class methods also take the
  215. # Day of Calendar Reform as an optional argument.
  216. #
  217. # Date objects are immutable once created.
  218. #
  219. # Once a Date has been created, date values
  220. # can be retrieved for the different date formats supported
  221. # using instance methods.  For instance, #mon() gives the
  222. # Civil month, #cwday() gives the Commercial day of the week,
  223. # and #yday() gives the Ordinal day of the year.  Date values
  224. # can be retrieved in any format, regardless of what format
  225. # was used to create the Date instance.
  226. #
  227. # The Date class includes the Comparable module, allowing
  228. # date objects to be compared and sorted, ranges of dates
  229. # to be created, and so forth.
  230. class Date
  231.  
  232.   include Comparable
  233.  
  234.   # Full month names, in English.  Months count from 1 to 12; a
  235.   # month's numerical representation indexed into this array
  236.   # gives the name of that month (hence the first element is nil).
  237.   MONTHNAMES = [nil] + %w(January February March April May June July
  238.               August September October November December)
  239.  
  240.   # Full names of days of the week, in English.  Days of the week
  241.   # count from 0 to 6 (except in the commercial week); a day's numerical
  242.   # representation indexed into this array gives the name of that day.
  243.   DAYNAMES = %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)
  244.  
  245.   # Abbreviated month names, in English.
  246.   ABBR_MONTHNAMES = [nil] + %w(Jan Feb Mar Apr May Jun
  247.                    Jul Aug Sep Oct Nov Dec)
  248.  
  249.   # Abbreviated day names, in English.
  250.   ABBR_DAYNAMES = %w(Sun Mon Tue Wed Thu Fri Sat)
  251.  
  252.   # The Julian Day Number of the Day of Calendar Reform for Italy
  253.   # and the Catholic countries.
  254.   ITALY     = 2299161 # 1582-10-15
  255.  
  256.   # The Julian Day Number of the Day of Calendar Reform for England
  257.   # and her Colonies.
  258.   ENGLAND   = 2361222 # 1752-09-14
  259.  
  260.   # A constant used to indicate that a Date should always use the
  261.   # Julian calendar.
  262.   JULIAN    = false
  263.  
  264.   # A constant used to indicate that a Date should always use the
  265.   # Gregorian calendar.
  266.   GREGORIAN = true
  267.  
  268.   # Does a given Julian Day Number fall inside the old-style (Julian)
  269.   # calendar?
  270.   #
  271.   # +jd+ is the Julian Day Number in question. +sg+ may be Date::GREGORIAN,
  272.   # in which case the answer is false; it may be Date::JULIAN, in which case
  273.   # the answer is true; or it may a number representing the Day of
  274.   # Calendar Reform. Date::ENGLAND and Date::ITALY are two possible such
  275.   # days.
  276.   def self.os? (jd, sg)
  277.     case sg
  278.     when Numeric; jd < sg
  279.     else;         not sg
  280.     end
  281.   end
  282.  
  283.   # Does a given Julian Day Number fall inside the new-style (Gregorian)
  284.   # calendar?
  285.   #
  286.   # The reverse of self.os?  See the documentation for that method for
  287.   # more details.
  288.   def self.ns? (jd, sg) not os?(jd, sg) end
  289.  
  290.   # Convert a Civil Date to a Julian Day Number.
  291.   # +y+, +m+, and +d+ are the year, month, and day of the
  292.   # month.  +sg+ specifies the Day of Calendar Reform.
  293.   #
  294.   # Returns the corresponding Julian Day Number.
  295.   def self.civil_to_jd(y, m, d, sg=GREGORIAN)
  296.     if m <= 2
  297.       y -= 1
  298.       m += 12
  299.     end
  300.     a = (y / 100.0).floor
  301.     b = 2 - a + (a / 4.0).floor
  302.     jd = (365.25 * (y + 4716)).floor +
  303.       (30.6001 * (m + 1)).floor +
  304.       d + b - 1524
  305.     if os?(jd, sg)
  306.       jd -= b
  307.     end
  308.     jd
  309.   end
  310.  
  311.   # Convert a Julian Day Number to a Civil Date.  +jd+ is
  312.   # the Julian Day Number. +sg+ specifies the Day of
  313.   # Calendar Reform.
  314.   #
  315.   # Returns the corresponding [year, month, day_of_month]
  316.   # as a three-element array.
  317.   def self.jd_to_civil(jd, sg=GREGORIAN)
  318.     if os?(jd, sg)
  319.       a = jd
  320.     else
  321.       x = ((jd - 1867216.25) / 36524.25).floor
  322.       a = jd + 1 + x - (x / 4.0).floor
  323.     end
  324.     b = a + 1524
  325.     c = ((b - 122.1) / 365.25).floor
  326.     d = (365.25 * c).floor
  327.     e = ((b - d) / 30.6001).floor
  328.     dom = b - d - (30.6001 * e).floor
  329.     if e <= 13
  330.       m = e - 1
  331.       y = c - 4716
  332.     else
  333.       m = e - 13
  334.       y = c - 4715
  335.     end
  336.     return y, m, dom
  337.   end
  338.  
  339.   # Convert an Ordinal Date to a Julian Day Number.
  340.   #
  341.   # +y+ and +d+ are the year and day-of-year to convert.
  342.   # +sg+ specifies the Day of Calendar Reform.
  343.   #
  344.   # Returns the corresponding Julian Day Number.
  345.   def self.ordinal_to_jd(y, d, sg=GREGORIAN)
  346.     civil_to_jd(y, 1, d, sg)
  347.   end
  348.  
  349.   # Convert a Julian Day Number to an Ordinal Date.
  350.   #
  351.   # +jd+ is the Julian Day Number to convert.
  352.   # +sg+ specifies the Day of Calendar Reform.
  353.   #
  354.   # Returns the corresponding Ordinal Date as
  355.   # [year, day_of_year]
  356.   def self.jd_to_ordinal(jd, sg=GREGORIAN)
  357.     y = jd_to_civil(jd, sg)[0]
  358.     doy = jd - civil_to_jd(y - 1, 12, 31, ns?(jd, sg))
  359.     return y, doy
  360.   end
  361.  
  362.   # Convert a Julian Day Number to a Commercial Date
  363.   #
  364.   # +jd+ is the Julian Day Number to convert.
  365.   # +sg+ specifies the Day of Calendar Reform.
  366.   #
  367.   # Returns the corresponding Commercial Date as
  368.   # [commercial_year, week_of_year, day_of_week]
  369.   def self.jd_to_commercial(jd, sg=GREGORIAN)
  370.     ns = ns?(jd, sg)
  371.     a = jd_to_civil(jd - 3, ns)[0]
  372.     y = if jd >= commercial_to_jd(a + 1, 1, 1, ns) then a + 1 else a end
  373.     w = 1 + ((jd - commercial_to_jd(y, 1, 1, ns)) / 7).floor
  374.     d = (jd + 1) % 7
  375.     if d.zero? then d = 7 end
  376.     return y, w, d
  377.   end
  378.  
  379.   # Convert a Commercial Date to a Julian Day Number.
  380.   #
  381.   # +y+, +w+, and +d+ are the (commercial) year, week of the year,
  382.   # and day of the week of the Commercial Date to convert.
  383.   # +sg+ specifies the Day of Calendar Reform.
  384.   def self.commercial_to_jd(y, w, d, ns=GREGORIAN)
  385.     jd = civil_to_jd(y, 1, 4, ns)
  386.     (jd - (((jd - 1) + 1) % 7)) +
  387.       7 * (w - 1) +
  388.       (d - 1)
  389.   end
  390.  
  391.   %w(self.clfloor clfloor).each do |name|
  392.     module_eval <<-"end;"
  393.       def #{name}(x, y=1)
  394.     q, r = x.divmod(y)
  395.     q = q.to_i
  396.     return q, r
  397.       end
  398.     end;
  399.   end
  400.  
  401.   private_class_method :clfloor
  402.   private              :clfloor
  403.  
  404.  
  405.   # Convert an Astronomical Julian Day Number to a (civil) Julian
  406.   # Day Number.
  407.   #
  408.   # +ajd+ is the Astronomical Julian Day Number to convert. 
  409.   # +of+ is the offset from UTC as a fraction of a day (defaults to 0).
  410.   #
  411.   # Returns the (civil) Julian Day Number as [day_number,
  412.   # fraction] where +fraction+ is always 1/2.
  413.   def self.ajd_to_jd(ajd, of=0) clfloor(ajd + of + 1.to_r/2) end
  414.  
  415.   # Convert a (civil) Julian Day Number to an Astronomical Julian
  416.   # Day Number.
  417.   #
  418.   # +jd+ is the Julian Day Number to convert, and +fr+ is a
  419.   # fractional day. 
  420.   # +of+ is the offset from UTC as a fraction of a day (defaults to 0).
  421.   #
  422.   # Returns the Astronomical Julian Day Number as a single
  423.   # numeric value.
  424.   def self.jd_to_ajd(jd, fr, of=0) jd + fr - of - 1.to_r/2 end
  425.  
  426.   # Convert a fractional day +fr+ to [hours, minutes, seconds,
  427.   # fraction_of_a_second]
  428.   def self.day_fraction_to_time(fr)
  429.     h,   fr = clfloor(fr, 1.to_r/24)
  430.     min, fr = clfloor(fr, 1.to_r/1440)
  431.     s,   fr = clfloor(fr, 1.to_r/86400)
  432.     return h, min, s, fr
  433.   end
  434.  
  435.   # Convert an +h+ hour, +min+ minutes, +s+ seconds period
  436.   # to a fractional day.
  437.   def self.time_to_day_fraction(h, min, s)
  438.     h.to_r/24 + min.to_r/1440 + s.to_r/86400
  439.   end
  440.  
  441.   # Convert an Astronomical Modified Julian Day Number to an
  442.   # Astronomical Julian Day Number.
  443.   def self.amjd_to_ajd(amjd) amjd + 4800001.to_r/2 end
  444.  
  445.   # Convert an Astronomical Julian Day Number to an
  446.   # Astronomical Modified Julian Day Number.
  447.   def self.ajd_to_amjd(ajd) ajd - 4800001.to_r/2 end
  448.  
  449.   # Convert a Modified Julian Day Number to a Julian
  450.   # Day Number.
  451.   def self.mjd_to_jd(mjd) mjd + 2400001 end
  452.  
  453.   # Convert a Julian Day Number to a Modified Julian Day
  454.   # Number.
  455.   def self.jd_to_mjd(jd) jd - 2400001 end
  456.  
  457.   # Convert a count of the number of days since the adoption
  458.   # of the Gregorian Calendar (in Italy) to a Julian Day Number.
  459.   def self.ld_to_jd(ld) ld + 2299160 end
  460.  
  461.   # Convert a Julian Day Number to the number of days since
  462.   # the adoption of the Gregorian Calendar (in Italy).
  463.   def self.jd_to_ld(jd) jd - 2299160 end
  464.  
  465.   # Convert a Julian Day Number to the day of the week.
  466.   #
  467.   # Sunday is day-of-week 0; Saturday is day-of-week 6.
  468.   def self.jd_to_wday(jd) (jd + 1) % 7 end
  469.  
  470.   # Is a year a leap year in the Julian calendar?
  471.   #
  472.   # All years divisible by 4 are leap years in the Julian calendar.
  473.   def self.julian_leap? (y) y % 4 == 0 end
  474.  
  475.   # Is a year a leap year in the Gregorian calendar?
  476.   #
  477.   # All years divisible by 4 are leap years in the Gregorian calendar,
  478.   # except for years divisible by 100 and not by 400.
  479.   def self.gregorian_leap? (y) y % 4 == 0 and y % 100 != 0 or y % 400 == 0 end
  480.  
  481.   class << self; alias_method :leap?, :gregorian_leap? end
  482.   class << self; alias_method :new0, :new end
  483.  
  484.   # Is +jd+ a valid Julian Day Number?
  485.   #
  486.   # If it is, returns it.  In fact, any value is treated as a valid
  487.   # Julian Day Number.
  488.   def self.valid_jd? (jd, sg=ITALY) jd end
  489.  
  490.   # Create a new Date object from a Julian Day Number.
  491.   #
  492.   # +jd+ is the Julian Day Number; if not specified, it defaults to
  493.   # 0. 
  494.   # +sg+ specifies the Day of Calendar Reform.
  495.   def self.jd(jd=0, sg=ITALY)
  496.     jd = valid_jd?(jd, sg)
  497.     new0(jd_to_ajd(jd, 0, 0), 0, sg)
  498.   end
  499.  
  500.   # Do the year +y+ and day-of-year +d+ make a valid Ordinal Date?
  501.   # Returns the corresponding Julian Day Number if they do, or
  502.   # nil if they don't.
  503.   #
  504.   # +d+ can be a negative number, in which case it counts backwards
  505.   # from the end of the year (-1 being the last day of the year).
  506.   # No year wraparound is performed, however, so valid values of
  507.   # +d+ are -365 .. -1, 1 .. 365 on a non-leap-year,
  508.   # -366 .. -1, 1 .. 366 on a leap year. 
  509.   # A date falling in the period skipped in the Day of Calendar Reform
  510.   # adjustment is not valid.
  511.   #
  512.   # +sg+ specifies the Day of Calendar Reform.
  513.   def self.valid_ordinal? (y, d, sg=ITALY)
  514.     if d < 0
  515.       ny, = clfloor(y + 1, 1)
  516.       jd = ordinal_to_jd(ny, d + 1, sg)
  517.       ns = ns?(jd, sg)
  518.       return unless [y] == jd_to_ordinal(jd, sg)[0..0]
  519.       return unless [ny, 1] == jd_to_ordinal(jd - d, ns)
  520.     else
  521.       jd = ordinal_to_jd(y, d, sg)
  522.       return unless [y, d] == jd_to_ordinal(jd, sg)
  523.     end
  524.     jd
  525.   end
  526.  
  527.   # Create a new Date object from an Ordinal Date, specified
  528.   # by year +y+ and day-of-year +d+. +d+ can be negative,
  529.   # in which it counts backwards from the end of the year.
  530.   # No year wraparound is performed, however.  An invalid
  531.   # value for +d+ results in an ArgumentError being raised.
  532.   #
  533.   # +y+ defaults to -4712, and +d+ to 1; this is Julian Day
  534.   # Number day 0.
  535.   #
  536.   # +sg+ specifies the Day of Calendar Reform.
  537.   def self.ordinal(y=-4712, d=1, sg=ITALY)
  538.     unless jd = valid_ordinal?(y, d, sg)
  539.       raise ArgumentError, 'invalid date'
  540.     end
  541.     new0(jd_to_ajd(jd, 0, 0), 0, sg)
  542.   end
  543.  
  544.   # Do year +y+, month +m+, and day-of-month +d+ make a
  545.   # valid Civil Date?  Returns the corresponding Julian
  546.   # Day Number if they do, nil if they don't.
  547.   #
  548.   # +m+ and +d+ can be negative, in which case they count
  549.   # backwards from the end of the year and the end of the
  550.   # month respectively.  No wraparound is performed, however,
  551.   # and invalid values cause an ArgumentError to be raised.
  552.   # A date falling in the period skipped in the Day of Calendar
  553.   # Reform adjustment is not valid.
  554.   #
  555.   # +sg+ specifies the Day of Calendar Reform.
  556.   def self.valid_civil? (y, m, d, sg=ITALY)
  557.     if m < 0
  558.       m += 13
  559.     end
  560.     if d < 0
  561.       ny, nm = clfloor(y * 12 + m, 12)
  562.       nm,    = clfloor(nm + 1, 1)
  563.       jd = civil_to_jd(ny, nm, d + 1, sg)
  564.       ns = ns?(jd, sg)
  565.       return unless [y, m] == jd_to_civil(jd, sg)[0..1]
  566.       return unless [ny, nm, 1] == jd_to_civil(jd - d, ns)
  567.     else
  568.       jd = civil_to_jd(y, m, d, sg)
  569.       return unless [y, m, d] == jd_to_civil(jd, sg)
  570.     end
  571.     jd
  572.   end
  573.  
  574.   class << self; alias_method :valid_date?, :valid_civil? end
  575.  
  576.   # Create a new Date object for the Civil Date specified by
  577.   # year +y+, month +m+, and day-of-month +d+.
  578.   #
  579.   # +m+ and +d+ can be negative, in which case they count
  580.   # backwards from the end of the year and the end of the
  581.   # month respectively.  No wraparound is performed, however,
  582.   # and invalid values cause an ArgumentError to be raised.
  583.   # can be negative
  584.   #
  585.   # +y+ defaults to -4712, +m+ to 1, and +d+ to 1; this is
  586.   # Julian Day Number day 0.
  587.   #
  588.   # +sg+ specifies the Day of Calendar Reform.
  589.   def self.civil(y=-4712, m=1, d=1, sg=ITALY)
  590.     unless jd = valid_civil?(y, m, d, sg)
  591.       raise ArgumentError, 'invalid date'
  592.     end
  593.     new0(jd_to_ajd(jd, 0, 0), 0, sg)
  594.   end
  595.  
  596.   class << self; alias_method :new, :civil end
  597.  
  598.   # Do year +y+, week-of-year +w+, and day-of-week +d+ make a
  599.   # valid Commercial Date?  Returns the corresponding Julian
  600.   # Day Number if they do, nil if they don't.
  601.   #
  602.   # Monday is day-of-week 1; Sunday is day-of-week 7.
  603.   #
  604.   # +w+ and +d+ can be negative, in which case they count
  605.   # backwards from the end of the year and the end of the
  606.   # week respectively.  No wraparound is performed, however,
  607.   # and invalid values cause an ArgumentError to be raised.
  608.   # A date falling in the period skipped in the Day of Calendar
  609.   # Reform adjustment is not valid.
  610.   #
  611.   # +sg+ specifies the Day of Calendar Reform.
  612.   def self.valid_commercial? (y, w, d, sg=ITALY)
  613.     if d < 0
  614.       d += 8
  615.     end
  616.     if w < 0
  617.       w = jd_to_commercial(commercial_to_jd(y + 1, 1, 1) + w * 7)[1]
  618.     end
  619.     jd = commercial_to_jd(y, w, d)
  620.     return unless ns?(jd, sg)
  621.     return unless [y, w, d] == jd_to_commercial(jd)
  622.     jd
  623.   end
  624.  
  625.   # Create a new Date object for the Commercial Date specified by
  626.   # year +y+, week-of-year +w+, and day-of-week +d+.
  627.   #
  628.   # Monday is day-of-week 1; Sunday is day-of-week 7.
  629.   #
  630.   # +w+ and +d+ can be negative, in which case they count
  631.   # backwards from the end of the year and the end of the
  632.   # week respectively.  No wraparound is performed, however,
  633.   # and invalid values cause an ArgumentError to be raised.
  634.   #
  635.   # +y+ defaults to 1582, +w+ to 41, and +d+ to 5, the Day of
  636.   # Calendar Reform for Italy and the Catholic countries.
  637.   #
  638.   # +sg+ specifies the Day of Calendar Reform.
  639.   def self.commercial(y=1582, w=41, d=5, sg=ITALY)
  640.     unless jd = valid_commercial?(y, w, d, sg)
  641.       raise ArgumentError, 'invalid date'
  642.     end
  643.     new0(jd_to_ajd(jd, 0, 0), 0, sg)
  644.   end
  645.  
  646.   def self.new_with_hash(elem, sg)
  647.     elem ||= {}
  648.     y, m, d = elem.values_at(:year, :mon, :mday)
  649.     if [y, m, d].include? nil
  650.       raise ArgumentError, '3 elements of civil date are necessary'
  651.     else
  652.       civil(y, m, d, sg)
  653.     end
  654.   end
  655.  
  656.   private_class_method :new_with_hash
  657.  
  658.   # Create a new Date object by parsing from a String
  659.   # according to a specified format.
  660.   #
  661.   # +str+ is a String holding a date representation.
  662.   # +fmt+ is the format that the date is in.  See
  663.   # date/format.rb for details on supported formats.
  664.   #
  665.   # The default +str+ is '-4712-01-01', and the default
  666.   # +fmt+ is '%F', which means Year-Month-Day_of_Month.
  667.   # This gives Julian Day Number day 0.
  668.   #
  669.   # +sg+ specifies the Day of Calendar Reform.
  670.   #
  671.   # An ArgumentError will be raised if +str+ cannot be
  672.   # parsed.
  673.   def self.strptime(str='-4712-01-01', fmt='%F', sg=ITALY)
  674.     elem = _strptime(str, fmt)
  675.     new_with_hash(elem, sg)
  676.   end
  677.  
  678.   # Create a new Date object by parsing from a String,
  679.   # without specifying the format.
  680.   #
  681.   # +str+ is a String holding a date representation. 
  682.   # +comp+ specifies whether to interpret 2-digit years
  683.   # as 19XX (>= 69) or 20XX (< 69); the default is not to.
  684.   # The method will attempt to parse a date from the String
  685.   # using various heuristics; see #_parse in date/format.rb
  686.   # for more details.  If parsing fails, an ArgumentError
  687.   # will be raised.
  688.   #
  689.   # The default +str+ is '-4712-01-01'; this is Julian
  690.   # Day Number day 0.
  691.   #
  692.   # +sg+ specifies the Day of Calendar Reform.
  693.   def self.parse(str='-4712-01-01', comp=false, sg=ITALY)
  694.     elem = _parse(str, comp)
  695.     new_with_hash(elem, sg)
  696.   end
  697.  
  698.   # Create a new Date object representing today.
  699.   #
  700.   # +sg+ specifies the Day of Calendar Reform.
  701.   def self.today(sg=ITALY)
  702.     jd = civil_to_jd(*(Time.now.to_a[3..5].reverse << sg))
  703.     new0(jd_to_ajd(jd, 0, 0), 0, sg)
  704.   end
  705.  
  706.   class << self
  707.  
  708.     def once(*ids) # :nodoc:
  709.       for id in ids
  710.     module_eval <<-"end;", __FILE__, __LINE__
  711.       alias_method :__#{id.to_i}__, :#{id.to_s}
  712.       private :__#{id.to_i}__
  713.       def #{id.to_s}(*args, &block)
  714.             if defined? @__#{id.to_i}__
  715.               @__#{id.to_i}__
  716.             elsif ! self.frozen?
  717.           @__#{id.to_i}__ ||= __#{id.to_i}__(*args, &block)
  718.             else
  719.                __#{id.to_i}__(*args, &block)
  720.             end
  721.       end
  722.     end;
  723.       end
  724.     end
  725.  
  726.     private :once
  727.  
  728.   end
  729.  
  730.   # *NOTE* this is the documentation for the method new0().  If
  731.   # you are reading this as the documentation for new(), that is
  732.   # because rdoc doesn't fully support the aliasing of the
  733.   # initialize() method.
  734.   # new() is in
  735.   # fact an alias for #civil(): read the documentation for that
  736.   # method instead.
  737.   #
  738.   # Create a new Date object.
  739.   #
  740.   # +ajd+ is the Astronomical Julian Day Number.
  741.   # +of+ is the offset from UTC as a fraction of a day.
  742.   # Both default to 0.
  743.   #
  744.   # +sg+ specifies the Day of Calendar Reform to use for this
  745.   # Date object.
  746.   #
  747.   # Using one of the factory methods such as Date::civil is
  748.   # generally easier and safer.
  749.   def initialize(ajd=0, of=0, sg=ITALY) @ajd, @of, @sg = ajd, of, sg end
  750.  
  751.   # Get the date as an Astronomical Julian Day Number.
  752.   def ajd() @ajd end
  753.  
  754.   # Get the date as an Astronomical Modified Julian Day Number.
  755.   def amjd() self.class.ajd_to_amjd(@ajd) end
  756.  
  757.   once :amjd
  758.  
  759.   # Get the date as a Julian Day Number.
  760.   def jd() self.class.ajd_to_jd(@ajd, @of)[0] end
  761.  
  762.   # Get any fractional day part of the date.
  763.   def day_fraction() self.class.ajd_to_jd(@ajd, @of)[1] end
  764.  
  765.   # Get the date as a Modified Julian Day Number.
  766.   def mjd() self.class.jd_to_mjd(jd) end
  767.  
  768.   # Get the date as the number of days since the Day of Calendar
  769.   # Reform (in Italy and the Catholic countries).
  770.   def ld() self.class.jd_to_ld(jd) end
  771.  
  772.   once :jd, :day_fraction, :mjd, :ld
  773.  
  774.   # Get the date as a Civil Date, [year, month, day_of_month]
  775.   def civil() self.class.jd_to_civil(jd, @sg) end
  776.  
  777.   # Get the date as an Ordinal Date, [year, day_of_year]
  778.   def ordinal() self.class.jd_to_ordinal(jd, @sg) end
  779.  
  780.   # Get the date as a Commercial Date, [year, week_of_year, day_of_week]
  781.   def commercial() self.class.jd_to_commercial(jd, @sg) end
  782.  
  783.   once :civil, :ordinal, :commercial
  784.   private :civil, :ordinal, :commercial
  785.  
  786.   # Get the year of this date.
  787.   def year() civil[0] end
  788.  
  789.   # Get the day-of-the-year of this date.
  790.   #
  791.   # January 1 is day-of-the-year 1
  792.   def yday() ordinal[1] end
  793.  
  794.   # Get the month of this date.
  795.   #
  796.   # January is month 1.
  797.   def mon() civil[1] end
  798.  
  799.   # Get the day-of-the-month of this date.
  800.   def mday() civil[2] end
  801.  
  802.   alias_method :month, :mon
  803.   alias_method :day, :mday
  804.  
  805.   # Get the time of this date as [hours, minutes, seconds,
  806.   # fraction_of_a_second]
  807.   def time() self.class.day_fraction_to_time(day_fraction) end
  808.  
  809.   once :time
  810.   private :time
  811.  
  812.   # Get the hour of this date.
  813.   def hour() time[0] end
  814.  
  815.   # Get the minute of this date.
  816.   def min() time[1] end
  817.  
  818.   # Get the second of this date.
  819.   def sec() time[2] end
  820.  
  821.   # Get the fraction-of-a-second of this date.
  822.   def sec_fraction() time[3] end
  823.  
  824.   private :hour, :min, :sec, :sec_fraction
  825.  
  826.   def zone() strftime('%Z') end
  827.  
  828.   private :zone
  829.  
  830.   # Get the commercial year of this date.  See *Commercial* *Date*
  831.   # in the introduction for how this differs from the normal year.
  832.   def cwyear() commercial[0] end
  833.  
  834.   # Get the commercial week of the year of this date.
  835.   def cweek() commercial[1] end
  836.  
  837.   # Get the commercial day of the week of this date.  Monday is
  838.   # commercial day-of-week 1; Sunday is commercial day-of-week 7.
  839.   def cwday() commercial[2] end
  840.  
  841.   # Get the week day of this date.  Sunday is day-of-week 0;
  842.   # Saturday is day-of-week 6.
  843.   def wday() self.class.jd_to_wday(jd) end
  844.  
  845.   once :wday
  846.  
  847.   # Is the current date old-style (Julian Calendar)?
  848.   def os? () self.class.os?(jd, @sg) end
  849.  
  850.   # Is the current date new-style (Gregorian Calendar)?
  851.   def ns? () self.class.ns?(jd, @sg) end
  852.  
  853.   once :os?, :ns?
  854.  
  855.   # Is this a leap year?
  856.   def leap?
  857.     self.class.jd_to_civil(self.class.civil_to_jd(year, 3, 1, ns?) - 1,
  858.              ns?)[-1] == 29
  859.   end
  860.  
  861.   once :leap?
  862.  
  863.   # When is the Day of Calendar Reform for this Date object?
  864.   def start() @sg end
  865.  
  866.   # Create a copy of this Date object using a new Day of Calendar Reform.
  867.   def new_start(sg=self.class::ITALY) self.class.new0(@ajd, @of, sg) end
  868.  
  869.   # Create a copy of this Date object that uses the Italian/Catholic
  870.   # Day of Calendar Reform.
  871.   def italy() new_start(self.class::ITALY) end
  872.  
  873.   # Create a copy of this Date object that uses the English/Colonial
  874.   # Day of Calendar Reform.
  875.   def england() new_start(self.class::ENGLAND) end
  876.  
  877.   # Create a copy of this Date object that always uses the Julian
  878.   # Calendar.
  879.   def julian() new_start(self.class::JULIAN) end
  880.  
  881.   # Create a copy of this Date object that always uses the Gregorian
  882.   # Calendar.
  883.   def gregorian() new_start(self.class::GREGORIAN) end
  884.  
  885.   def offset() @of end
  886.   def new_offset(of=0) self.class.new0(@ajd, of, @sg) end
  887.  
  888.   private :offset, :new_offset
  889.  
  890.   # Return a new Date object that is +n+ days later than the
  891.   # current one.
  892.   #
  893.   # +n+ may be a negative value, in which case the new Date
  894.   # is earlier than the current one; however, #-() might be
  895.   # more intuitive.
  896.   #
  897.   # If +n+ is not a Numeric, a TypeError will be thrown.  In
  898.   # particular, two Dates cannot be added to each other.
  899.   def + (n)
  900.     case n
  901.     when Numeric; return self.class.new0(@ajd + n, @of, @sg)
  902.     end
  903.     raise TypeError, 'expected numeric'
  904.   end
  905.  
  906.   # If +x+ is a Numeric value, create a new Date object that is
  907.   # +x+ days earlier than the current one.
  908.   #
  909.   # If +x+ is a Date, return the number of days between the
  910.   # two dates; or, more precisely, how many days later the current
  911.   # date is than +x+.
  912.   #
  913.   # If +x+ is neither Numeric nor a Date, a TypeError is raised.
  914.   def - (x)
  915.     case x
  916.     when Numeric; return self.class.new0(@ajd - x, @of, @sg)
  917.     when Date;    return @ajd - x.ajd
  918.     end
  919.     raise TypeError, 'expected numeric or date'
  920.   end
  921.  
  922.   # Compare this date with another date.
  923.   #
  924.   # +other+ can also be a Numeric value, in which case it is
  925.   # interpreted as an Astronomical Julian Day Number.
  926.   #
  927.   # Comparison is by Astronomical Julian Day Number, including
  928.   # fractional days.  This means that both the time and the
  929.   # timezone offset are taken into account when comparing
  930.   # two DateTime instances.  When comparing a DateTime instance
  931.   # with a Date instance, the time of the latter will be
  932.   # considered as falling on midnight UTC.
  933.   def <=> (other)
  934.     case other
  935.     when Numeric; return @ajd <=> other
  936.     when Date;    return @ajd <=> other.ajd
  937.     end
  938.     nil
  939.   end
  940.  
  941.   # The relationship operator for Date.
  942.   #
  943.   # Compares dates by Julian Day Number.  When comparing
  944.   # two DateTime instances, or a DateTime with a Date,
  945.   # the instances will be regarded as equivalent if they
  946.   # fall on the same date in local time.
  947.   def === (other)
  948.     case other
  949.     when Numeric; return jd == other
  950.     when Date;    return jd == other.jd
  951.     end
  952.     false
  953.   end
  954.  
  955.   # Return a new Date object that is +n+ months later than
  956.   # the current one.
  957.   #
  958.   # If the day-of-the-month of the current Date is greater
  959.   # than the last day of the target month, the day-of-the-month
  960.   # of the returned Date will be the last day of the target month.
  961.   def >> (n)
  962.     y, m = clfloor(year * 12 + (mon - 1) + n, 12)
  963.     m,   = clfloor(m + 1, 1)
  964.     d = mday
  965.     d -= 1 until jd2 = self.class.valid_civil?(y, m, d, ns?)
  966.     self + (jd2 - jd)
  967.   end
  968.  
  969.   # Return a new Date object that is +n+ months earlier than
  970.   # the current one.
  971.   #
  972.   # If the day-of-the-month of the current Date is greater
  973.   # than the last day of the target month, the day-of-the-month
  974.   # of the returned Date will be the last day of the target month.
  975.   def << (n) self >> -n end
  976.  
  977.   # Step the current date forward +step+ days at a
  978.   # time (or backward, if +step+ is negative) until
  979.   # we reach +limit+ (inclusive), yielding the resultant
  980.   # date at each step.
  981.   def step(limit, step)  # :yield: date
  982.     da = self
  983.     op = [:-,:<=,:>=][step<=>0]
  984.     while da.__send__(op, limit)
  985.       yield da
  986.       da += step
  987.     end
  988.     self
  989.   end
  990.  
  991.   # Step forward one day at a time until we reach +max+
  992.   # (inclusive), yielding each date as we go.
  993.   def upto(max, &block)  # :yield: date
  994.       step(max, +1, &block)
  995.   end
  996.  
  997.   # Step backward one day at a time until we reach +min+
  998.   # (inclusive), yielding each date as we go.
  999.   def downto(min, &block) # :yield: date
  1000.       step(min, -1, &block)
  1001.   end
  1002.  
  1003.   # Return a new Date one day after this one.
  1004.   def succ() self + 1 end
  1005.  
  1006.   alias_method :next, :succ
  1007.  
  1008.   # Is this Date equal to +other+?
  1009.   #
  1010.   # +other+ must both be a Date object, and represent the same date.
  1011.   def eql? (other) Date === other and self == other end
  1012.  
  1013.   # Calculate a hash value for this date.
  1014.   def hash() @ajd.hash end
  1015.  
  1016.   # Return internal object state as a programmer-readable string.
  1017.   def inspect() format('#<%s: %s,%s,%s>', self.class, @ajd, @of, @sg) end
  1018.  
  1019.   # Return the date as a human-readable string.
  1020.   #
  1021.   # The format used is YYYY-MM-DD.
  1022.   def to_s() strftime end
  1023.  
  1024.   # Dump to Marshal format.
  1025.   def _dump(limit) Marshal.dump([@ajd, @of, @sg], -1) end
  1026.  
  1027. # def self._load(str) new0(*Marshal.load(str)) end
  1028.  
  1029.   # Load from Marshall format.
  1030.   def self._load(str)
  1031.     a = Marshal.load(str)
  1032.     if a.size == 2
  1033.       ajd,     sg = a
  1034.            of = 0
  1035.       ajd -= 1.to_r/2
  1036.     else
  1037.       ajd, of, sg = a
  1038.     end
  1039.     new0(ajd, of, sg)
  1040.   end
  1041.  
  1042. end
  1043.  
  1044. # Class representing a date and time.
  1045. #
  1046. # See the documentation to the file date.rb for an overview.
  1047. #
  1048. # DateTime objects are immutable once created.
  1049. #
  1050. # == Other methods.
  1051. #
  1052. # The following methods are defined in Date, but declared private
  1053. # there.  They are made public in DateTime.  They are documented
  1054. # here.
  1055. #
  1056. # === hour()
  1057. #
  1058. # Get the hour-of-the-day of the time.  This is given
  1059. # using the 24-hour clock, counting from midnight.  The first
  1060. # hour after midnight is hour 0; the last hour of the day is
  1061. # hour 23.
  1062. #
  1063. # === min()
  1064. #
  1065. # Get the minute-of-the-hour of the time.
  1066. #
  1067. # === sec()
  1068. #
  1069. # Get the second-of-the-minute of the time.
  1070. #
  1071. # === sec_fraction()
  1072. #
  1073. # Get the fraction of a second of the time.  This is returned as
  1074. # a +Rational+.
  1075. #
  1076. # === zone()
  1077. #
  1078. # Get the time zone as a String.  This is representation of the
  1079. # time offset such as "+1000", not the true time-zone name.
  1080. #
  1081. # === offset()
  1082. #
  1083. # Get the time zone offset as a fraction of a day.  This is returned
  1084. # as a +Rational+.
  1085. #
  1086. # === new_offset(of=0)
  1087. #
  1088. # Create a new DateTime object, identical to the current one, except
  1089. # with a new time zone offset of +of+.  +of+ is the new offset from
  1090. # UTC as a fraction of a day.
  1091. #
  1092. class DateTime < Date
  1093.  
  1094.   # Do hour +h+, minute +min+, and second +s+ constitute a valid time?
  1095.   #
  1096.   # If they do, returns their value as a fraction of a day.  If not,
  1097.   # returns nil.
  1098.   #
  1099.   # The 24-hour clock is used.  Negative values of +h+, +min+, and
  1100.   # +sec+ are treating as counting backwards from the end of the
  1101.   # next larger unit (e.g. a +min+ of -2 is treated as 58).  No
  1102.   # wraparound is performed.
  1103.   def self.valid_time? (h, min, s)
  1104.     h   += 24 if h   < 0
  1105.     min += 60 if min < 0
  1106.     s   += 60 if s   < 0
  1107.     return unless (0..24) === h and
  1108.           (0..59) === min and
  1109.           (0..59) === s
  1110.     time_to_day_fraction(h, min, s)
  1111.   end
  1112.  
  1113.   # Create a new DateTime object corresponding to the specified
  1114.   # Julian Day Number +jd+ and hour +h+, minute +min+, second +s+.
  1115.   #
  1116.   # The 24-hour clock is used.  Negative values of +h+, +min+, and
  1117.   # +sec+ are treating as counting backwards from the end of the
  1118.   # next larger unit (e.g. a +min+ of -2 is treated as 58).  No
  1119.   # wraparound is performed.  If an invalid time portion is specified,
  1120.   # an ArgumentError is raised.
  1121.   #
  1122.   # +of+ is the offset from UTC as a fraction of a day (defaults to 0).
  1123.   # +sg+ specifies the Day of Calendar Reform.
  1124.   #
  1125.   # All day/time values default to 0.
  1126.   def self.jd(jd=0, h=0, min=0, s=0, of=0, sg=ITALY)
  1127.     unless (jd = valid_jd?(jd, sg)) and
  1128.        (fr = valid_time?(h, min, s))
  1129.       raise ArgumentError, 'invalid date'
  1130.     end
  1131.     new0(jd_to_ajd(jd, fr, of), of, sg)
  1132.   end
  1133.  
  1134.   # Create a new DateTime object corresponding to the specified
  1135.   # Ordinal Date and hour +h+, minute +min+, second +s+.
  1136.   #
  1137.   # The 24-hour clock is used.  Negative values of +h+, +min+, and
  1138.   # +sec+ are treating as counting backwards from the end of the
  1139.   # next larger unit (e.g. a +min+ of -2 is treated as 58).  No
  1140.   # wraparound is performed.  If an invalid time portion is specified,
  1141.   # an ArgumentError is raised.
  1142.   #
  1143.   # +of+ is the offset from UTC as a fraction of a day (defaults to 0).
  1144.   # +sg+ specifies the Day of Calendar Reform.
  1145.   #
  1146.   # +y+ defaults to -4712, and +d+ to 1; this is Julian Day Number
  1147.   # day 0.  The time values default to 0.
  1148.   def self.ordinal(y=-4712, d=1, h=0, min=0, s=0, of=0, sg=ITALY)
  1149.     unless (jd = valid_ordinal?(y, d, sg)) and
  1150.        (fr = valid_time?(h, min, s))
  1151.       raise ArgumentError, 'invalid date'
  1152.     end
  1153.     new0(jd_to_ajd(jd, fr, of), of, sg)
  1154.   end
  1155.  
  1156.   # Create a new DateTime object corresponding to the specified
  1157.   # Civil Date and hour +h+, minute +min+, second +s+.
  1158.   #
  1159.   # The 24-hour clock is used.  Negative values of +h+, +min+, and
  1160.   # +sec+ are treating as counting backwards from the end of the
  1161.   # next larger unit (e.g. a +min+ of -2 is treated as 58).  No
  1162.   # wraparound is performed.  If an invalid time portion is specified,
  1163.   # an ArgumentError is raised.
  1164.   #
  1165.   # +of+ is the offset from UTC as a fraction of a day (defaults to 0).
  1166.   # +sg+ specifies the Day of Calendar Reform.
  1167.   #
  1168.   # +y+ defaults to -4712, +m+ to 1, and +d+ to 1; this is Julian Day
  1169.   # Number day 0.  The time values default to 0.
  1170.   def self.civil(y=-4712, m=1, d=1, h=0, min=0, s=0, of=0, sg=ITALY)
  1171.     unless (jd = valid_civil?(y, m, d, sg)) and
  1172.        (fr = valid_time?(h, min, s))
  1173.       raise ArgumentError, 'invalid date'
  1174.     end
  1175.     new0(jd_to_ajd(jd, fr, of), of, sg)
  1176.   end
  1177.  
  1178.   class << self; alias_method :new, :civil end
  1179.  
  1180.   # Create a new DateTime object corresponding to the specified
  1181.   # Commercial Date and hour +h+, minute +min+, second +s+.
  1182.   #
  1183.   # The 24-hour clock is used.  Negative values of +h+, +min+, and
  1184.   # +sec+ are treating as counting backwards from the end of the
  1185.   # next larger unit (e.g. a +min+ of -2 is treated as 58).  No
  1186.   # wraparound is performed.  If an invalid time portion is specified,
  1187.   # an ArgumentError is raised.
  1188.   #
  1189.   # +of+ is the offset from UTC as a fraction of a day (defaults to 0).
  1190.   # +sg+ specifies the Day of Calendar Reform.
  1191.   #
  1192.   # +y+ defaults to 1582, +w+ to 41, and +d+ to 5; this is the Day of
  1193.   # Calendar Reform for Italy and the Catholic countries.
  1194.   # The time values default to 0.
  1195.   def self.commercial(y=1582, w=41, d=5, h=0, min=0, s=0, of=0, sg=ITALY)
  1196.     unless (jd = valid_commercial?(y, w, d, sg)) and
  1197.        (fr = valid_time?(h, min, s))
  1198.       raise ArgumentError, 'invalid date'
  1199.     end
  1200.     new0(jd_to_ajd(jd, fr, of), of, sg)
  1201.   end
  1202.  
  1203.   def self.new_with_hash(elem, sg)
  1204.     elem ||= {}
  1205.     y, m, d, h, min, s, fr, of =
  1206.       elem.values_at(:year, :mon, :mday,
  1207.              :hour, :min, :sec, :sec_fraction, :offset)
  1208.     h   ||= 0
  1209.     min ||= 0
  1210.     s   ||= 0
  1211.     fr  ||= 0
  1212.     of  ||= 0
  1213.     if [y, m, d].include? nil
  1214.       raise ArgumentError, '3 elements of civil date are necessary'
  1215.     else
  1216.       civil(y, m, d, h, min, s, of.to_r/86400, sg) + (fr/86400)
  1217.     end
  1218.   end
  1219.  
  1220.   private_class_method :new_with_hash
  1221.  
  1222.   # Create a new DateTime object by parsing from a String
  1223.   # according to a specified format.
  1224.   #
  1225.   # +str+ is a String holding a date-time representation.
  1226.   # +fmt+ is the format that the date-time is in.  See
  1227.   # date/format.rb for details on supported formats.
  1228.   #
  1229.   # The default +str+ is '-4712-01-01T00:00:00Z', and the default
  1230.   # +fmt+ is '%FT%T%Z'.  This gives midnight on Julian Day Number day 0.
  1231.   #
  1232.   # +sg+ specifies the Day of Calendar Reform.
  1233.   #
  1234.   # An ArgumentError will be raised if +str+ cannot be
  1235.   # parsed.
  1236.   def self.strptime(str='-4712-01-01T00:00:00Z', fmt='%FT%T%Z', sg=ITALY)
  1237.     elem = _strptime(str, fmt)
  1238.     new_with_hash(elem, sg)
  1239.   end
  1240.  
  1241.   # Create a new DateTime object by parsing from a String,
  1242.   # without specifying the format.
  1243.   #
  1244.   # +str+ is a String holding a date-time representation. 
  1245.   # +comp+ specifies whether to interpret 2-digit years
  1246.   # as 19XX (>= 69) or 20XX (< 69); the default is not to.
  1247.   # The method will attempt to parse a date-time from the String
  1248.   # using various heuristics; see #_parse in date/format.rb
  1249.   # for more details.  If parsing fails, an ArgumentError
  1250.   # will be raised.
  1251.   #
  1252.   # The default +str+ is '-4712-01-01T00:00:00Z'; this is Julian
  1253.   # Day Number day 0.
  1254.   #
  1255.   # +sg+ specifies the Day of Calendar Reform.
  1256.   def self.parse(str='-4712-01-01T00:00:00Z', comp=false, sg=ITALY)
  1257.     elem = _parse(str, comp)
  1258.     new_with_hash(elem, sg)
  1259.   end
  1260.  
  1261.   class << self; undef_method :today end rescue nil
  1262.  
  1263.   # Create a new DateTime object representing the current time.
  1264.   #
  1265.   # +sg+ specifies the Day of Calendar Reform.
  1266.   def self.now(sg=ITALY)
  1267.     i = Time.now
  1268.     a = i.to_a[0..5].reverse
  1269.     jd = civil_to_jd(*(a[0,3] << sg))
  1270.     fr = time_to_day_fraction(*(a[3,3])) + i.usec.to_r/86400000000
  1271.     of = i.utc_offset.to_r/86400
  1272.     new0(jd_to_ajd(jd, fr, of), of, sg)
  1273.   end
  1274.  
  1275.   public :hour, :min, :sec, :sec_fraction, :zone, :offset, :new_offset
  1276.  
  1277. end
  1278.  
  1279. class Date
  1280.  
  1281.   [ %w(exist1?    valid_jd?),
  1282.     %w(exist2?    valid_ordinal?),
  1283.     %w(exist3?    valid_date?),
  1284.     %w(exist?    valid_date?),
  1285.     %w(existw?    valid_commercial?),
  1286.     %w(new1    jd),
  1287.     %w(new2    ordinal),
  1288.     %w(new3    new),
  1289.     %w(neww    commercial)
  1290.   ].each do |old, new|
  1291.     module_eval <<-"end;"
  1292.       def self.#{old}(*args, &block)
  1293.     if $VERBOSE
  1294.       warn("\#{caller.shift.sub(/:in .*/, '')}: " \
  1295.            "warning: \#{self}::#{old} is deprecated; " \
  1296.            "use \#{self}::#{new}")
  1297.     end
  1298.     #{new}(*args, &block)
  1299.       end
  1300.     end;
  1301.   end
  1302.  
  1303.   [ %w(sg    start),
  1304.     %w(newsg    new_start),
  1305.     %w(of    offset),
  1306.     %w(newof    new_offset)
  1307.   ].each do |old, new|
  1308.     module_eval <<-"end;"
  1309.       def #{old}(*args, &block)
  1310.     if $VERBOSE
  1311.       warn("\#{caller.shift.sub(/:in .*/, '')}: " \
  1312.            "warning: \#{self.class}\##{old} is deprecated; " \
  1313.            "use \#{self.class}\##{new}")
  1314.     end
  1315.     #{new}(*args, &block)
  1316.       end
  1317.     end;
  1318.   end
  1319.  
  1320.   private :of, :newof
  1321.  
  1322. end
  1323.  
  1324. class DateTime < Date
  1325.  
  1326.   public :of, :newof
  1327.  
  1328. end
  1329.